package com.hssy.wululuaplan.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hssy.wululuaplan.entity.*;
import com.hssy.wululuaplan.exception.CustomException;
import com.hssy.wululuaplan.form.CourseScheduleForm;
import com.hssy.wululuaplan.mapper.*;
import com.hssy.wululuaplan.service.CourseScheduleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hssy.wululuaplan.vo.ClassRecordVo;
import com.hssy.wululuaplan.vo.CourseScheduleVo;
import com.hssy.wululuaplan.vo.CourseScheduleVo2;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Mr.Hongtao
 * @since 2024-02-28
 */
@Service("courseSchedule")
public class CourseScheduleServiceImpl extends ServiceImpl<CourseScheduleMapper, CourseSchedule> implements CourseScheduleService {

    @Resource
    private AttendanceMapper attendanceMapper;

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private DivideClassMapper divideClassMapper;

    @Resource
    private StudentMapper studentMapper;

    @Override
    public CourseScheduleVo findAll() {

        List<ClassRecordVo> undoList = new ArrayList<>();
        List<ClassRecordVo> doingList = new ArrayList<>();
        List<ClassRecordVo> doneList = new ArrayList<>();

        Date current = DateUtil.date();

        // 查询全部课程计划
        List<CourseSchedule> list = baseMapper.selectList(null);
        // 得到所有的课程id，然后查出所需的全部课程信息，映射成map备用
        List<Integer> courseIds = list.stream().map(CourseSchedule::getCourseId).collect(Collectors.toList());
        List<Course> courseList = courseMapper.selectBatchIds(courseIds);
        Map<Integer, Course> courseMap = courseList.stream().collect(Collectors.toMap(Course::getId, Function.identity()));

        for (CourseSchedule courseSchedule : list) {
            Date start = courseSchedule.getStart();
            Date end = courseSchedule.getEnd();
            if (DateUtil.between(start, current, DateUnit.SECOND, false) > 0 &&
                DateUtil.between(end, current, DateUnit.SECOND, false) < 0 ){
                // 正在进行中
                ClassRecordVo vo = new ClassRecordVo();
                BeanUtils.copyProperties(courseSchedule, vo);
                Course course = courseMap.get(courseSchedule.getCourseId());
                vo.setCourseName(course.getCourseName());
                vo.setSession(course.getSession());
                vo.setTeacher(course.getTeacher());
                doingList.add(vo);
            }else if (DateUtil.between(start, current, DateUnit.SECOND, false) > 0 &&
                    DateUtil.between(end, current, DateUnit.SECOND, false) > 0) {
                // 已结束
                ClassRecordVo vo = new ClassRecordVo();
                BeanUtils.copyProperties(courseSchedule, vo);
                Course course = courseMap.get(courseSchedule.getCourseId());
                vo.setCourseName(course.getCourseName());
                vo.setSession(course.getSession());
                vo.setTeacher(course.getTeacher());
                doneList.add(vo);
            }else if (DateUtil.between(start, current, DateUnit.SECOND, false) < 0 &&
                    DateUtil.between(end, current, DateUnit.SECOND, false) < 0) {
                // 未开始
                ClassRecordVo vo = new ClassRecordVo();
                BeanUtils.copyProperties(courseSchedule, vo);
                Course course = courseMap.get(courseSchedule.getCourseId());
                vo.setCourseName(course.getCourseName());
                vo.setSession(course.getSession());
                vo.setTeacher(course.getTeacher());
                undoList.add(vo);
            }
        }

        CourseScheduleVo vo = new CourseScheduleVo();
        vo.setUndoList(undoList);
        vo.setDoingList(doingList);
        vo.setDoneList(doneList);

        return vo;
    }

    @Override
    @Transactional
    public void create(CourseScheduleForm form) {
        // 暂时不做限制，任意添加
        // 新增计划，同时将该计划的涉及的学生加入到班级中
        CourseSchedule entity = new CourseSchedule();
        BeanUtils.copyProperties(form, entity);
        String start = form.getStart();
        DateTime startTime = DateUtil.parse(start, "yyyy-MM-dd HH:mm");
        DateTime endTime = DateUtil.parse(
                DateUtil.format(DateUtil.offsetHour(startTime, 1),
                "yyyy-MM-dd HH:mm"), "yyyy-MM-dd HH:mm");
        entity.setStart(startTime);
        // entity.setEnd(endTime);
        baseMapper.insert(entity);

        // 课程id
        Integer courseId = form.getCourseId();
        List<DivideClass> list = divideClassMapper.selectList(Wrappers.<DivideClass>lambdaQuery()
                .eq(DivideClass::getCourseId, courseId));
        if (list.size() > 0) {
            List<Integer> studentIds = list.stream().map(DivideClass::getStudentId).collect(Collectors.toList());
            Map<Integer, String> studentMap = studentMapper.selectList(Wrappers.<Student>lambdaQuery()
                    .in(Student::getId, studentIds)).stream()
                    .collect(Collectors.toMap(Student::getId, Student::getStudentName));
            for (DivideClass divideClass : list) {
                Attendance attendance = new Attendance();
                attendance.setStudentId(divideClass.getStudentId());
                attendance.setScheduleId(entity.getId());
                attendance.setStatus(0);
            }
        }

    }

    @Override
    @Transactional
    public void edit(CourseScheduleForm form) {
        // 如果有签到，则不可以修改
        Attendance attendance = attendanceMapper.selectById(form.getId());
        if (attendance != null) {
            throw new CustomException(-200,"已有签到记录，不可以修改该课程计划");
        }
        // 没有签到，直接修改
        CourseSchedule entity = new CourseSchedule();
        Date startTime = DateUtil.parse(form.getStart(), "yyyy-MM-dd HH:mm");
        Date endTime = DateUtil.parse(form.getEnd(), "yyyy-MM-dd HH:mm");
        entity.setId(form.getId());
        entity.setCourseId(form.getCourseId());
        entity.setStart(startTime);
        entity.setEnd(endTime);
        baseMapper.updateById(entity);
    }

    @Override
    @Transactional
    public int delete(Integer id) {
        // 如果有签到，则不可以删除
        Attendance attendance = attendanceMapper.selectOne(Wrappers.<Attendance>lambdaQuery()
                .eq(Attendance::getScheduleId, id));
        if (attendance != null) {
            // throw new CustomException(-200,"已有签到记录，不可以修改该课程计划");
            return -200;
        }
        // 没有签到，直接删除
        baseMapper.deleteById(id);
        return 1;
    }

    @Override
    public ClassRecordVo findById(Integer id) {
        CourseSchedule courseSchedule = baseMapper.selectById(id);
        ClassRecordVo vo = new ClassRecordVo();
        if (courseSchedule != null) {
            BeanUtils.copyProperties(courseSchedule, vo);
            String format = DateUtil.format(courseSchedule.getStart(), "yyyy-MM-dd HH:mm");
            vo.setClassTime(format);
            Course course = courseMapper.selectById(courseSchedule.getCourseId());
            if (course != null) {
                vo.setCourseName(course.getCourseName());
                vo.setSession(course.getSession());
                vo.setTeacher(course.getTeacher());
            }
        }
        return vo;
    }

    @Override
    public List<CourseScheduleVo2> getAll(Integer status) {
        return null;
    }

}
